//
//  WZGOrderComitCheckView.m
//  ZCJZ
//
//  Created by 潘洪波 on 2020/1/15.
//  Copyright © 2020 jeking. All rights reserved.
//

#import "WZGOrderComitCheckView.h"
#import "ZCOrderCheckGoodsInfoCell.h"
#import "ZCOrderCheckLeftAndRightCell.h"
#import "WZGOrderCheckSubtotalCell.h"
#import "WZGOrderCheckItemModel.h"
#import "WZGAddressModel.h"
#import "WZGOrderCommitCheckCell.h"
#import "TBCityIconFont.h"
#import <MJExtension.h>

@interface WZGOrderComitCheckView ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UIView *backgroudV;
@property (weak, nonatomic) IBOutlet UIImageView *addrImgView;
@property (weak, nonatomic) IBOutlet UILabel *addrUserNameLab;
@property (weak, nonatomic) IBOutlet UILabel *addrUserAddrLab;
@property (weak, nonatomic) IBOutlet UITableView *mTableView;
@property (weak, nonatomic) IBOutlet UIButton *comfirmBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;

@property (nonatomic, assign) CGRect myFrame ;
@property (nonatomic, copy) ActionCallback actionCall ;
@property (nonatomic, copy) NSDictionary *dataDict ;
@property (nonatomic, copy) NSArray *dataArray ;//固定数据
@property (nonatomic, copy) NSArray *goodsArray ;//商品种类

@property (nonatomic, assign) CGFloat frieght_fee ;//运费
@property (nonatomic, assign) CGFloat insurance_fee ;//退换省心
@property (nonatomic, assign) CGFloat diff_fee ;//下单立减
@property (nonatomic, assign) CGFloat coupon_fee ;//优惠券
@property (nonatomic, assign) CGFloat actual_fee ;//实付
@property (nonatomic, assign) CGFloat total_fee ;//总价格
@property (nonatomic, assign) NSInteger total_num ,total_goods ;//总件数，种类
@property (nonatomic, strong) NSMutableArray *goodsItems ;//商品总类(包括不同商品、相同商品不同规格)
@property (nonatomic, strong) NSMutableArray *priceArray ;

@property (nonatomic, strong) WZGAddressModel *address ;

@end


@implementation WZGOrderComitCheckView

/// <#Description#>
/// @param supView <#supView description#>
/// @param dict <#dict description#>
/// @param callback <#callback description#>
+ (instancetype)showViewOnView:(nullable UIView*)supView
                      withData:(nullable NSDictionary*)dict
                    completion:(nullable ActionCallback)callback{
    UIView *v = nil;
    if (supView) {
        v = supView;
    }else{
        v = [UIApplication sharedApplication].keyWindow;
    }
    WZGOrderComitCheckView *checkView = [[WZGOrderComitCheckView alloc] initWithFrame:v.bounds];
    [v addSubview:checkView];
    checkView.dataDict = dict;
    checkView.actionCall = callback;
    [checkView showView];
    return checkView;
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self = [[UINib nibWithNibName:@"WZGOrderComitCheckView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
        [self.mTableView registerNib:[UINib nibWithNibName:@"ZCOrderCheckGoodsInfoCell" bundle:nil] forCellReuseIdentifier:@"ZCOrderCheckGoodsInfoCell"];
        [self.mTableView registerNib:[UINib nibWithNibName:@"ZCOrderCheckLeftAndRightCell" bundle:nil] forCellReuseIdentifier:@"ZCOrderCheckLeftAndRightCell"];
        [self.mTableView registerNib:[UINib nibWithNibName:@"WZGOrderCheckSubtotalCell" bundle:nil] forCellReuseIdentifier:@"WZGOrderCheckSubtotalCell"];
        [self.mTableView registerNib:[UINib nibWithNibName:@"WZGOrderCommitCheckCell" bundle:nil] forCellReuseIdentifier:@"WZGOrderCommitCheckCell"];
        self.mTableView.delegate = self;
        self.mTableView.dataSource = self;
        self.mTableView.estimatedRowHeight = 50;
        
        self.myFrame = frame;
        self.backgroudV.transform = CGAffineTransformMakeScale(0.00001, 0.00001);
        self.goodsItems = [NSMutableArray array];
        self.priceArray = [NSMutableArray array];
        
        self.cancelBtn.layer.borderColor = [generalToolBox getColorWithHexadecimalColorStr:@"0xD9D9D9"].CGColor;
        self.cancelBtn.layer.borderWidth = 1;
        [self.comfirmBtn setBackgroundColor:[UIColor redColor]];
        //&#xe621;
        self.addrImgView.image = [UIImage imageNamed:@"icon_check_addr"];
        
        self.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideV)];
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        
    }
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.frame = _myFrame;
}

#pragma mark ---- gestureDelegate ----
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isDescendantOfView:self.backgroudV]) {
        return NO;
    }
    return YES;
}

- (void)setDataDict:(NSDictionary *)dataDict{
    _dataDict = dataDict;
    if (dataDict) {
        self.mTableView.hidden = NO;
        self.address = [dataDict valueForKey:@"address"];
        self.addrUserNameLab.text = [NSString stringWithFormat:@"%@     %@",self.address.name,self.address.phone];
        self.addrUserAddrLab.text = self.address.full_address;
        self.goodsArray = @[];
        NSArray *goods = [dataDict objectForKey:@"goods"];
        if ( goods.count > 0 ) {
            self.goodsArray = goods;
            
            self.total_num = 0;
            for (WZGOrderCheckItemModel* model in goods) {
                // 1、计算商品总价  2、计算商品总运费 3、计算退换省心费用 4、计算商品件数、种类
                self.diff_fee += model.diff_fee;
                for (OrderItemsModel *item in model.items) {
                    self.total_num += item.nums;
                    self.total_fee += item.shop_price*item.nums;
                    [self.goodsItems addObject:item];
                }
                self.total_goods = 1;
                self.frieght_fee += model.freight_fee;
                if (model.choosen) {
                    self.insurance_fee += model.insurance_fee;
                }
            }
            self.actual_fee = [[dataDict valueForKey:@"total_actual_fee"] floatValue];
            self.coupon_fee = [[dataDict valueForKey:@"coupon_fee"] floatValue];
        }
        [self initPriceArray];
        [self.mTableView reloadData];
    }else{
        self.goodsArray = @[];
        self.mTableView.hidden = YES;
    }
}

- (void)initPriceArray{
    if (!self.priceArray) {
        self.priceArray = [NSMutableArray array];
    }
    [self.priceArray addObject:[NSString stringWithFormat:@"￥%.2f",self.total_fee]];
    [self.priceArray addObject:[NSString stringWithFormat:@"￥%.2f",self.frieght_fee]];
    [self.priceArray addObject:[NSString stringWithFormat:@"￥%.2f",self.insurance_fee]];
    [self.priceArray addObject:[NSString stringWithFormat:@"-￥%.2f",self.diff_fee]];
    [self.priceArray addObject:[NSString stringWithFormat:@"-￥%.2f",self.coupon_fee]];
}

- (IBAction)cancelBtnAction:(id)sender {
    [self hideView:nil];
}

- (IBAction)commitAction:(id)sender {
    WeakSelf(self);
    [self hideView:^{
        if (weakself.actionCall) {
            weakself.actionCall(1);
        }
    }];
}

- (void)hideV{
    [self hideView:nil];
}

- (void)showView{
    
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroudV.transform = CGAffineTransformMakeScale(1, 1);
    }];
}

- (void)hideView:(void(^)(void))complete{
    [UIView animateWithDuration:0.3 animations:^{
        self.backgroudV.transform = CGAffineTransformMakeScale(0.00001, 0.00001);
    } completion:^(BOOL finished) {
        if (complete) {
            complete();
        }
        [self.backgroudV removeFromSuperview];
        [self removeFromSuperview];
    }];
}

#pragma mark - UITableViewDataSource
#pragma mark -

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.total_goods + self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.total_goods) {
        ZCOrderCheckGoodsInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderCheckGoodsInfoCell"];
        OrderItemsModel *item = [self.goodsItems objectAtIndex:indexPath.row];
        cell.dict = [item mj_keyValues];
        return cell;
    }else if ( indexPath.row == ([tableView numberOfRowsInSection:0] - 1) ){
        WZGOrderCheckSubtotalCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WZGOrderCheckSubtotalCell"];
        cell.subTotalLabel.text = [NSString stringWithFormat:@"￥%.2f",self.actual_fee];
        cell.keyStrLabel.text = @"实付款";
        cell.backgroundColor = [UIColor whiteColor];
        cell.contentView.backgroundColor = [UIColor whiteColor];
        cell.lineview.hidden = NO;
        return cell;
    }else {
        NSInteger row = indexPath.row;
        if (row == self.total_goods) {
            WZGOrderCommitCheckCell *cell = [tableView dequeueReusableCellWithIdentifier:@"WZGOrderCommitCheckCell"];
            cell.goodsKindLabel.text = [NSString stringWithFormat:@"%ld",self.total_goods];
            cell.numLabel.text = [NSString stringWithFormat:@"%ld",self.total_num];
            return cell;
        }else{
            ZCOrderCheckLeftAndRightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCOrderCheckLeftAndRightCell"];
            cell.keystr = self.dataArray[row-self.total_goods];
            cell.valuestr = self.priceArray[row-self.total_goods-1];
            return cell;
        }
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger row = indexPath.row ;
    if (row < self.total_goods) {
        return UITableViewAutomaticDimension;
    }else if (row == self.total_goods){
        return 40;
    }else if (row == (self.total_goods + self.dataArray.count-1)){
        return 44;
    }
    return 30;
}

- (NSArray *)dataArray{
    return @[@"",@"商品总计",@"订单运费",@"退换省心",@"下单立减",@"优惠券",@"优惠券"];
}



@end
